import { createVNode, VNode, render as vueRender } from 'vue';
import { IContext, IOpenViewResult, IParam, IViewDetail } from '@/core';
import Drawer from '@components/common/drawer/drawer.vue';

export class DrawerHelper {
	/**
	 * @description 抽屉唯一实例
	 * @private
	 * @static
	 * @memberof DrawerHelper
	 */
	private static readonly drawerInstance = new DrawerHelper();

	/**
	 * vue 实例
	 *
	 * @private
	 * @type {Vue | null}
	 * @memberof DrawerHelper
	 */
	private vueExample: VNode | null = null;

	/**
	 * @description 抽屉容器
	 * @private
	 * @type {(Node | null)}
	 * @memberof DrawerHelper
	 */
	private container: Node | null = null;

	/**
	 * 构造方法
	 *
	 * @memberof DrawerHelper
	 */
	constructor() {
		if (DrawerHelper.drawerInstance) {
			return DrawerHelper.drawerInstance;
		}
	}

	/**
	 * @description 获取实例
	 * @static
	 * @return {*}
	 * @memberof DrawerHelper
	 */
	static getInstance() {
		return DrawerHelper.drawerInstance;
	}

	/**
	 * @description 打开模态
	 * @param {IViewDetail} view
	 * @param {IParam} params
	 * @return {*}  {(Subject<any> | void)}
	 * @memberof DrawerHelper
	 */
	public openDrawer(
		view: IViewDetail,
		context: IContext,
		viewParams: IParam,
		placement: string = 'bottom'
	): Promise<IOpenViewResult> {
		return new Promise((resolve, reject) => {
			try {
				this.container = document.createElement('div');
				document.body.appendChild(this.container);
				this.vueExample = createVNode(Drawer, {
					view,
					context,
					viewParams,
					placement,
					onDrawerAction: (result: IOpenViewResult) => {
						if (result) {
							resolve(result);
						}
						if (this.vueExample) {
							this.vueExample = null;
						}
						if (this.container) {
							document.body.removeChild(this.container);
							this.container = null;
						}
					},
				});
				const appInstance = App.getUIAppInstance();
				if (appInstance) {
					this.vueExample.appContext = appInstance.appContext;
				}
				vueRender(this.vueExample, this.container as any);
			} catch (error) {
				reject(error);
			}
		});
	}
}
